<template>
  <el-dialog
      title="选择LOGO"
      :with-header="false"
      :append-to-body="true"
      :visible.sync="visible"
      custom-class="layer_wrap select_picture"
      :before-close="() => handleClose()">
    <div class="layer_inside">
      <div class="layer_header">
        <span class="title">选择LOGO</span>
        <i class="el-icon-close" @click="() => handleClose()"/>
      </div>
      <div class="layer_main_wrap">
        <div class="layer_delete_main" :key="widgetKey">
          <el-table
              border
              height="400"
              ref="elTable"
              :data="tableData"
              class="table-area"
              @select="handleSelectRow"
              :row-key="(row) => row.id"
          >
            <el-table-column type="selection" :reserve-selection="true"/>
            <el-table-column prop="name" label="素材名称">
              <template v-slot="scope">
                <div class="name-inside" slot="reference"> {{ (scope.row.name) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="素材类型" width="120">
              <template v-slot="scope">
                <div>{{ scope.row.type }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
              <template v-slot="scope">
                <div>{{ scope.row.createTime }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="true">
              <template v-slot="scope">
                <el-row class="operator-box">
                  <el-col :push="8" :span="8" class="edit item" title="预览">
                    <div class="image_preview">
                      <el-image
                          lazy
                          ref="previewImg"
                          :src="`${scope.row.url}?t=${getOnlyId()}`"
                          :preview-src-list="[`${scope.row.url}?t=${getOnlyId()}`]"
                      />
                    </div>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="layer_delete_bottom">
          <el-button class="button_item cancel" @click="() => handleClose()">取消</el-button>
          <el-button class="button_item sure" type="primary" @click="() => handleSure()">确认</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {v4 as uuid} from "uuid";
import {ModelDesignApi} from "@/api/modeldesign";

export default {
  components: {},
  props: ["visible", 'info'],
  name: "SelectPicture",
  data() {
    return {
      radio: 1,
      tableData: [],
      selectedRow: {},
      previewList: Array(),
      pictureSrc: '',
      widgetKey: uuid(),
      header: require("@/components/assets/images/design/header.jpeg"),
    };
  },

  computed: {
    //生成唯一的字符串
    getOnlyId() {
      return function () {
        return uuid()
      }
    },
  },

  methods: {
    // 关闭
    handleClose() {
      this.$emit("handleCancel", false);
    },

    // 确认
    handleSure() {
      if (!!(this.selectedRow)) {
        this.handleClose();
        let params = Object();
        Reflect.set(params, 'val', this.$lodash.cloneDeep(this.selectedRow));
        Reflect.set(params, 'key', this.info.updataType);
        Reflect.set(params, 'number', (this.info.number));
        Reflect.set(this.selectedRow, 'number', (this.info.number));
        Reflect.set(this.selectedRow, 'key', (this.info.updataType));
        Reflect.set(this.selectedRow, 'val', this.selectedRow)
        this.$emit('handleSure', params)
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择图片',
        })
      }
    },

    // select方法
    handleSelectRow(selection, val) {
      // 接收两个参数，selection为所有选中数据的集合，val为当前选择的数据
      // 先将所有选中的数据变为未选中状态
      this.$refs.elTable.clearSelection();
      // 如果选择完当前数据后selection为空数组，说明现在是取消勾选，无选中数据
      if (selection.length === 0) {
        this.selectedRow = Object();  // 清空data中绑定的selectedRow
        return
      }
      // 切换最近一次选择数据的状态
      this.handleToggleSelection([val],'elTable')
      // 更新data中的selectedRow
      this.selectedRow = val;
      console.log(this.selectedRow)
    },

    // 回显选中的数据
    handleToggleSelection(rows,tableRef) {
      console.log('进入选中的函数')
      if (rows) {
        rows.forEach((row) => {
          // 切换选中状态
          this.$refs[tableRef].toggleRowSelection(row, true)
        })
      } else {
        // 清空选中
        this.$refs[tableRef].clearSelection()
      }
    },

    // 预览图片
    handlePreview(row) {
      this.previewList = [`${row.url}?t=${this.getOnlyId()}`];
      this.pictureSrc = `${row.url}?t=${this.getOnlyId()}`;
    },
  },


  watch: {
    visible: {
      handler: async function (val) {
        const self = this;
        if (val) {
          let params = Object();
          self.widgetKey = uuid();
          Reflect.set(params, 'name', '');
          Reflect.set(params, 'classification', 'logo')
          Reflect.set(params, 'deptIds', Array())
          Reflect.set(params, 'pageNum', '1')
          Reflect.set(params, 'pageSize', '9999')
          try {
            const resp = await ModelDesignApi.getAllMaterial(params);
            if (resp && (resp.code) === 200) {
              self.$nextTick(()=>{
                let rows = [self.info?.content?.val] || Array();
                const rowIds = self.$lodash.map(rows, 'id');
                // 选中的对象
                let selectionInfo = self.$lodash.filter(resp.data, function(items) {
                  return rowIds.includes(items.id);
                });
                this.handleToggleSelection(selectionInfo,'elTable')
              })
              self.tableData = (resp.data);
            }
          } catch (e) {
            let {data} = (e.response);
            console.log(data)
          }
        }
      },
      deep: true,
      immediate: false,
    },
  }
};
</script>


<style lang="scss" scoped>
.layer_delete_main {
  :deep(.table-area th.el-table__cell .el-checkbox) {
    display: none !important;
  }
}
</style>

<style lang="scss" scoped>
@import "@/components/assets/style/layer";
@import "./assets/style";
</style>